/**
 * Copyright 2013 Bhushan
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package org.s4j.sample;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.s4j.signals.annotation.Slot;
import org.s4j.signals.core.Bridgeable;

/**
 * Beeper is a singleton that can be used to manage beeps across the system.
 * 
 * @author Bhushan
 * 
 */
public class Beeper implements Bridgeable {
    private static int INITIAL_DELAY_MS = 50;
    private static int INTERVAL_MS = 1000;
    private static int PAUSE_TIMEOUT = 2000;

    private static Beeper INSTANCE;
    private Timer timer;
    private Set<Device> requesters;
    private boolean timerRunning;

    private Beeper() {
        timer = new Timer();
        requesters = new HashSet<Device>();
        timerRunning = false;
    }

    public static Beeper getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Beeper();
        }
        return INSTANCE;
    }

    @Slot("StartBeep")
    public synchronized void startBeep(final Device table) {
        requesters.add(table);
        if (!timerRunning) {
            timerRunning = true;
            timer.scheduleAtFixedRate(createNewTask(), INITIAL_DELAY_MS, INTERVAL_MS);
        }
    }

    @Slot("StopBeep")
    public synchronized void stopBeep(final Device table) {
        requesters.remove(table);
        if (requesters.isEmpty()) {
            timer.cancel();
            timer = new Timer();
            timerRunning = false;
        }
    }

    /**
     * Makes the beeper pause for a while. This is helpful in case we need to pause beeping for some time to allow for
     * user action.
     */
    @Slot("PauseBeep")
    public synchronized void pause() {
        if (timerRunning) {
            timer.cancel();
            timer = new Timer();
            timer.scheduleAtFixedRate(createNewTask(), PAUSE_TIMEOUT, INTERVAL_MS);
        }
    }

    private TimerTask createNewTask() {
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                Logger.LogEvent("!!! Beep...");
            }
        };
        return task;
    }
}
